#include <stdio.h>
#include <stdlib.h>
#include "mylib.h"
#include <sys/types.h>
#include <fcntl.h>

#ifndef SIZE
#define SIZE 512 /*dimensione per il buffer di lettura/scrittura*/
#endif

int main(int argc, char *args[]){
    int fd;
    int i, n, currpos, dastampare;
    int stop;
    char buf[SIZE];
    if (argc < 2) {
		fprintf(stderr,"Specify at least one argument.\n");
		exit(1);
	}
	
	for(i=1; i < argc; i++){
	
		printf("********** file: %s ***********\n", args[i]);
        fd = open(args[i], O_RDONLY, 777);
        
        if(fd == -1){
		    syserr(args[0], "Apertura del file");
		}
		lseek(fd, 0, SEEK_END); /* posiziono il puntantore del byte all'ultimo */
		stop=0;
		n = 0;
		while(!stop){
		    if(lseek(fd, -2, SEEK_CUR) == -1){
		        stop = 1;
		        lseek(fd, 0, SEEK_SET);
		        n++;
		    }else
		        n += read(fd, buf, 1);
		    if(buf[0] == '\n' || stop){
		        currpos = lseek(fd, 0, SEEK_CUR);
		        while(n > 0){
		            if(n > SIZE){
		                read(fd, buf, SIZE);
		                n -= write(1, buf, SIZE);
		            }else{
		                read(fd, buf, n);
		                n -= write(1, buf, n);
		            }
		        }
		        lseek(fd, currpos, SEEK_SET);
		    }
		}
		
    }
    
    
}
